package com.example.powermock.util;


import com.alibaba.fastjson.JSON;
import com.tencentcloudapi.billing.v20180709.BillingClient;
import com.tencentcloudapi.billing.v20180709.models.DescribeAccountBalanceRequest;
import com.tencentcloudapi.billing.v20180709.models.DescribeAccountBalanceResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.cvm.v20170312.CvmClient;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class TencentCloudMsgUtil {

    private static final String SMS_VALID_TIME = "10"; //min

    private static String secretId;
    private static String secretKey;
    private static String sdkAppId;
    private static String templateId;

    @Value("${tencentCloudMsg.secretId:}")
    public void setSecretId(String secretId) {
        TencentCloudMsgUtil.secretId = secretId;
    }

    @Value("${tencentCloudMsg.secretKey:}")
    public void setSecretKey(String secretKey) {
        TencentCloudMsgUtil.secretKey = secretKey;
    }

    @Value("${tencentCloudMsg.sdkAppId:}")
    public void setSdkAppId(String sdkAppId) {
        TencentCloudMsgUtil.sdkAppId = sdkAppId;
    }

    @Value("${tencentCloudMsg.templateId:}")
    public void setTemplateId(String templateId) {
        TencentCloudMsgUtil.templateId = templateId;
    }

    public static Map<String, String> send(String phone, String captchaCode, String signName) {
        Map<String, String> resultMap = new HashMap<>();
        try {
            SmsClient client = getSmsClient();

            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppId(sdkAppId);
            req.setSignName(signName);
            String senderid = "OKX";
            req.setSenderId(senderid);
            req.setTemplateId(templateId);
            String[] phoneNumberSet = {phone};
            req.setPhoneNumberSet(phoneNumberSet);
            String[] templateParamSet = {captchaCode, SMS_VALID_TIME};
            req.setTemplateParamSet(templateParamSet);
            SendSmsResponse res = client.SendSms(req);
            log.info("tencentCloud message send result:{}", SendSmsResponse.toJsonString(res));
            SendStatus[] sendStatusSet = res.getSendStatusSet();
            if (sendStatusSet == null || sendStatusSet.length < 1) {
                resultMap.put("MsgResultConstant.SUCCESS_KEY", "MsgResultConstant.FALSE_VALUE");
            } else {
                SendStatus sendStatus = sendStatusSet[0];
                String code = sendStatus.getCode();
                if ("ok".equalsIgnoreCase(code)) {
                    resultMap.put("MsgResultConstant.SUCCESS_KEY", "MsgResultConstant.TRUE_VALUE");
                    resultMap.put("MsgResultConstant.REQID_KEY", sendStatus.getSerialNo());
                } else {
                    resultMap.put("MsgResultConstant.RESULT_CODE", code);
                    resultMap.put("MsgResultConstant.RESULT_MSG", SendSmsResponse.toJsonString(res));
                    resultMap.put("MsgResultConstant.SUCCESS_KEY", "MsgResultConstant.FALSE_VALUE");
                }
            }
        } catch (TencentCloudSDKException e) {
            log.error("TencentCloudMsgUtil error", e);
            resultMap.put("MsgResultConstant.SUCCESS_KEY", "MsgResultConstant.FALSE_VALUE");
            resultMap.put("MsgResultConstant.RESULT_MSG", "请求腾讯云短信失败");
        }
        return resultMap;
    }

    public static void report(String sid) {
        log.info("tencentCloud report SMS verification records, sid:{}", sid);
        try {
            if (StringUtils.isEmpty(sid)) {
                log.warn("tencentCloud report param error, sid:{}", sid);
                return;
            }
            SmsClient smsClient = getSmsClient();
            ReportConversionRequest request = new ReportConversionRequest();
            request.setSmsSdkAppId(sdkAppId);
            request.setSerialNo(sid);
            long currentTimeMillis = System.currentTimeMillis();
            request.setConversionTime(currentTimeMillis / 1000L);
            ReportConversionResponse reportConversionResponse = smsClient.ReportConversion(request);
            ReportConversionStatus reportConversionStatus = reportConversionResponse.getReportConversionStatus();
            if (!"ok".equalsIgnoreCase(reportConversionStatus.getCode())) {
                log.warn("tencentCloud ReportConversion failed, sid:{}, resp:{}", sid, JSON.toJSONString(reportConversionResponse));
            }
        } catch (Exception e) {
            log.error("tencentCloud ReportConversion exception, sid:{}", sid, e);
        }
    }

    public static String balance() {
        try {
            Credential cred = new Credential(secretId, secretKey);
            BillingClient billingClient = new BillingClient(cred, "ap-singapore");
            DescribeAccountBalanceRequest request = new DescribeAccountBalanceRequest();
            DescribeAccountBalanceResponse response = billingClient.DescribeAccountBalance(request);
            return "Residual balance：" + response.getBalance().toString();
        } catch (Exception e) {
            log.error("tencentCloud get balance exception", e);
            return "Failed to get balance";
        }
    }

    private static SmsClient getSmsClient() {
        Credential cred = new Credential(secretId, secretKey);
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod("HmacSHA256");
        return new SmsClient(cred, "ap-singapore", clientProfile);
    }
}